package com.qfhd.soft.cjzcore.UI;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.qfhd.soft.cjzcore.CJZManager;
import com.qfhd.soft.cjzcore.Core.CJCore;
import com.qfhd.soft.cjzcore.Core.CJLogger;
import com.qfhd.soft.cjzcore.Handle.CJHandle;
import com.qfhd.soft.cjzcore.Handle.CJHandleObject;
import com.qfhd.soft.cjzcore.Handle.CJHanlderType;
import com.qfhd.soft.cjzcore.Model.Task_image_click_type;
import com.qfhd.soft.cjzcore.Model.Task_image_detail_model;
import com.qfhd.soft.cjzcore.Model.Task_image_detial_step_model;
import com.qfhd.soft.cjzcore.Model.Task_image_submit_model;
import com.qfhd.soft.cjzcore.Moudle.CJImgTaskHelper;
import com.qfhd.soft.cjzcore.R;
import com.qfhd.soft.cjzcore.UI.Base.BaseActivity;
import com.qfhd.soft.cjzcore.UI.CJBitmapHelper.CJBitmapHelper;
import com.qfhd.soft.cjzcore.UI.Core.CJActivityManager;
import com.qfhd.soft.cjzcore.UI.Core.CJCameraHelper;
import com.qfhd.soft.cjzcore.UI.Core.DecimalFormatHelper;
import com.qfhd.soft.cjzcore.UI.Custom.CJNaviBar;
import com.qfhd.soft.cjzcore.UI.Dialog.CJDialog;
import com.qfhd.soft.cjzcore.UI.Dialog.CJNormalDialog;
import com.qfhd.soft.cjzcore.UI.Dialog.MessageDialog;
import com.qfhd.soft.cjzcore.UI.Listener.CJListener;
import com.qfhd.soft.cjzcore.UI.MulitRecycle.adapter.MulitAdpter;
import com.qfhd.soft.cjzcore.UI.MulitRecycle.bean.Task_image_detail_section_bean;
import com.qfhd.soft.cjzcore.UI.MulitRecycle.bean.Task_image_submit_bean;
import com.qfhd.soft.cjzcore.UI.MulitRecycle.decorate.Visitable;
import com.qfhd.soft.cjzcore.UI.imageLook.CJImageLookHelper;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.qfhd.soft.cjzcore.Handle.CJHanlderWhatType.LoadFinish;

public class TaskImageActivity extends BaseActivity {
    private Context mContext;
    private Activity mActicity;

//    @BindView(R.id.task_image_detail_navi)
    CJNaviBar naviBar;
//    @BindView(R.id.task_image_detail_icon)
    QMUIRadiusImageView icon;
//    @BindView(R.id.task_image_detail_title)
    TextView tx_title;
//    @BindView(R.id.task_image_detail_money)
    TextView tx_money;
//    @BindView(R.id.task_image_detail_doneCount)
    TextView tx_doneCount;
//    @BindView(R.id.task_image_detail_doCount)
    TextView tx_doCount;
//    @BindView(R.id.task_image_detail_time)
    TextView tx_time;
//    @BindView(R.id.task_image_detail_submitText)
    TextView tx_submitText;
//    @BindView(R.id.task_image_detail_deviceTip)
    TextView tx_deviceTip;
//    @BindView(R.id.task_image_detail_step_recycle)
    RecyclerView step_recyclerView;
//    @BindView(R.id.task_image_detail_submit_recycleView)
    RecyclerView submit_recycleView;
//    @BindView(R.id.task_image_detail_submit)
    RelativeLayout submit_relativeL;

    private MulitAdpter step_adpter;
    private List<Visitable> step_adpterData = new ArrayList<>();
    private MulitAdpter submit_adpter;
    private List<Visitable> submit_adpterData = new ArrayList<>();
    private Task_image_detail_model model;
    private String tid;
    private QMUITipDialog waitDialog;

    private int taskId;
    private int submitId;
    private String filePath;//图片路径

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_image);
        mContext = this;
        mActicity = this;

        CJHandle.getInstance().register(new CJHandleObject(CJHanlderType.taskImage,myHandler));

        naviBar = (CJNaviBar) findViewById(R.id.task_image_detail_navi);
        icon = (QMUIRadiusImageView) findViewById(R.id.task_image_detail_icon);
        tx_title = (TextView) findViewById(R.id.task_image_detail_title);
        tx_money = (TextView) findViewById(R.id.task_image_detail_money);
        tx_doneCount = (TextView) findViewById(R.id.task_image_detail_doneCount);
        tx_time = (TextView) findViewById(R.id.task_image_detail_time);
        tx_submitText = (TextView) findViewById(R.id.task_image_detail_submitText);
        tx_deviceTip = (TextView) findViewById(R.id.task_image_detail_deviceTip);
        tx_doCount = (TextView) findViewById(R.id.task_image_detail_doCount);
        step_recyclerView = (RecyclerView) findViewById(R.id.task_image_detail_step_recycle);
        submit_recycleView = (RecyclerView) findViewById(R.id.task_image_detail_submit_recycleView);
        submit_relativeL = (RelativeLayout) findViewById(R.id.task_image_detail_submit);

        tid = getIntent().getStringExtra(CJActivityManager.Intent_Name_String);
        waitDialog = CJDialog.getTipDialog(CJDialog.CJDialog_TIP_TYPE_LOADING,mContext,"请稍等");

        loadData();
    }

    private void refreshUI(){
        tx_submitText.setText(model.getStatus());
        if(model.getEnableStatus()){
            submit_relativeL.setEnabled(true);
            submit_relativeL.setBackground(getResources().getDrawable(R.color.colorTheme));
        }
        else{
            submit_relativeL.setEnabled(false);
            submit_relativeL.setBackground(getResources().getDrawable(R.color.gray));
        }

    }

    private void initUI() {
        naviBar.setLeftBtnClickListener(v -> back());

        Glide.with(mContext).load(model.iconUrl).centerCrop().placeholder(getResources().getDrawable(R.drawable.placeholder)).into(icon);
        tx_title.setText(model.title);
        tx_money.setText("+" + DecimalFormatHelper.getFloat2(CJCore.getRealMoney_float(model.money)) + "元");
        tx_doneCount.setText("" + model.doneCount);
        tx_doCount.setText("" + (model.totalCount-model.doneCount));
        tx_time.setText("" + 48);
        tx_deviceTip.setText(model.getTaskTip());

        refreshUI();

        //操作步骤
        step_adpter = new MulitAdpter();

        step_recyclerView.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.VERTICAL, false));
        step_recyclerView.getItemAnimator().setChangeDuration(0);
        step_recyclerView.setHasFixedSize(true);
        step_recyclerView.setNestedScrollingEnabled(false);
        //解决数据加载完成后, 没有停留在顶部的问题
        step_recyclerView.setFocusable(false);
        step_recyclerView.setAdapter(step_adpter);

        //提交步骤
        submit_adpter = new MulitAdpter();

        submit_recycleView.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.VERTICAL, false));
        submit_recycleView.getItemAnimator().setChangeDuration(0);
        submit_recycleView.setHasFixedSize(true);
        submit_recycleView.setNestedScrollingEnabled(false);
        //解决数据加载完成后, 没有停留在顶部的问题
        submit_recycleView.setFocusable(false);
        submit_recycleView.setAdapter(submit_adpter);

        CJLogger.v("task image activity adpterData size:" + step_adpterData.size());
        submit_adpter.setList(submit_adpterData);
        step_adpter.setList(step_adpterData);


        initEvent();
    }

    private void initEvent(){
        submit_relativeL.setOnClickListener(v -> {
            if(isCanSubmit()){
                submit();
            }
            else{
                mActicity.runOnUiThread(()->{
                    CJCore.Toast(mContext,"请完善信息",false);
                });
            }
        });
    }

    private void loadData() {
        new Thread(()->{
            boolean ret = CJZManager.getInstance().taskImgGetDetail(tid);
            if(!ret){
                CJCore.ToastInMainThread(mActicity,mContext,"网络失败",false);
                back();
            }
            model = CJImgTaskHelper.getInstance().getDetailModel();
            for (int i = 0; i < model.steps.size(); i++) {
                Task_image_detial_step_model tmp = model.steps.get(i);
                Task_image_detail_section_bean bean = new Task_image_detail_section_bean(tmp, type -> {
                    switch (type){
                        case Task_image_click_type.ShowImage:{
                            CJLogger.v("ShowImage");
                            List<String> list_tmp = new ArrayList<>();
                            list_tmp.add(tmp.step_image);
                            mActicity.runOnUiThread(()->{
                                CJImageLookHelper.showImages(mContext,list_tmp);
                            });
                        }
                        break;
                        default:
                            break;
                    }
                }, mContext,i+1);
                step_adpterData.add(bean);
            }
            for (int i = 0; i < model.submits.size(); i++) {
                Task_image_submit_model tmp = model.submits.get(i);
                Task_image_submit_bean bean = new Task_image_submit_bean(tmp, mContext, type -> {
                    switch (type) {
                        case Task_image_click_type.AddImage: {
                            CJLogger.v("AddImage");
                            taskId = tmp.task_id;
                            submitId = tmp.id;
                            mActicity.runOnUiThread(() -> {
                                CJCameraHelper.getInstance().selectPic(mContext, mActicity);
                            });
                        }
                        break;
                        case Task_image_click_type.ShowImage: {
                            CJLogger.v("ShowImage");
                            if(!TextUtils.isEmpty(tmp.upImageUrl)){
                                List<String> list_tmp = new ArrayList<>();
                                list_tmp.add(tmp.upImageUrl);
                                CJImageLookHelper.showImages(mContext,list_tmp);
                            }
                        }
                        break;
                        case Task_image_click_type.ShowShiLiImage: {
                            CJLogger.v("ShowShiLiImage");
                            if(!TextUtils.isEmpty(tmp.exampleImage)){
                                List<String> list_tmp = new ArrayList<>();
                                list_tmp.add(tmp.exampleImage);
                                CJImageLookHelper.showImages(mContext,list_tmp);
                            }
                        }
                        break;
                        case Task_image_click_type.ClearImage: {
                            CJLogger.v("ClearImage");
                            tmp.upImageUrl = null;
                            mActicity.runOnUiThread(()->{
                                submit_adpter.setList(submit_adpterData);
                            });
                        }
                        break;
                        default:
                            break;
                    }
                });
                submit_adpterData.add(bean);
            }

//            CJEvent.TaskImage.getEventtBus().post(new CJEventObject(CJEventObjectType.LoadFinish, null));
            myHandler.sendEmptyMessage(LoadFinish);
        }).start();
    }

    @Override
    public void getMessage(Message msg) {
        super.getMessage(msg);
        if (msg == null) return;
        switch (msg.what) {
            case LoadFinish: {
                initUI();
            }
            break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            Bitmap bitmap = null;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),CJCameraHelper.getInstance().getUriImage());
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (bitmap != null && CJBitmapHelper.getInstance().saveBitmap(CJBitmapHelper.getInstance().compressBitmap(bitmap),"/uploadImg")) {
                if(CJCameraHelper.getInstance().getUriImage() != null){
                    String path = CJBitmapHelper.getInstance().getSavePath("uploadImg");
                    CJLogger.v("image path paizhao:" + path);
                    filePath = path;
                }

                if (!bitmap.isRecycled()) {
                    bitmap.recycle(); //回收图片所占的内存
                    System.gc(); //提醒系统及时回收
                }

                isUploadImg();
            }
            else{
                CJLogger.v("bitmap save error");
            }
        }
        if (requestCode == 0) {
            if (data != null) {
                Uri uri = data.getData();
                String path = CJCameraHelper.getInstance().getFilePath(uri,0,mContext);
                BitmapFactory.Options options = new BitmapFactory.Options();
                Bitmap bitmap = null;
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(CJBitmapHelper.getInstance().saveBitmap(CJBitmapHelper.getInstance().compressBitmap(bitmap),"/uploadImg")){
                    filePath = CJBitmapHelper.getInstance().getSavePath("/uploadImg");
                }
                else{
                    filePath = path;
                }
                CJLogger.v("image path xiance1:" + path);
            }
            isUploadImg();
        }
    }


    /**
     * 询问是否上传图片
     */
    private void isUploadImg(){
        new  CJNormalDialog(mActicity,mContext,"图片上传","确认上传？", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadImg();
            }
        });
//        CJDialog.getInstance().showNormalDialog(mContext,"图片上传","确认上传？",v -> {
//            uploadImg();
//        });
    }

    private void uploadImg(){
        waitDialog.show();
        new Thread(()->{
            List<String> tmp = new ArrayList<>();
            tmp.add(filePath);
            String ret = CJZManager.getInstance().uploadImg(tmp,taskId,submitId);
            if(!TextUtils.isEmpty(ret)){
                mActicity.runOnUiThread(()->{
                    waitDialog.dismiss();
                    for(int i=0; i<submit_adpterData.size(); i++){
                        Task_image_submit_bean bean = (Task_image_submit_bean)submit_adpterData.get(i);
                        if(bean.getModel().id == submitId){
                            bean.getModel().upImageUrl = ret;
                        }
                    }
                    CJCore.Toast(mContext,"上传成功",false);
                    submit_adpter.setList(submit_adpterData);
                });
            }
            else{
                mActicity.runOnUiThread(()->{
                    waitDialog.dismiss();
                    CJCore.Toast(mContext,"上传失败",false);
                });
            }
        }).start();
    }

    public boolean isCanSubmit(){
        boolean isCan = true;
        for(int i=0; i<model.submits.size(); i++){
            Task_image_submit_model tmp = (Task_image_submit_model)model.submits.get(i);
            if(tmp.type == 1){ //字符串
                if(TextUtils.isEmpty(tmp.textInput)){
                    return false;
                }
            }
            else if(tmp.type == 2){//图片
                if(TextUtils.isEmpty(tmp.upImageUrl)){
                    return false;
                }
            }
        }
        return isCan;
    }

    public String getResult(){
        JSONObject obj = new JSONObject();
        for(int i=0; i<model.submits.size(); i++){
            JSONObject subObj = new JSONObject();
            Task_image_submit_model tmp = (Task_image_submit_model)model.submits.get(i);
            try {
                subObj.put("require_type", tmp.type);
                if (tmp.type == 1) { //字符串
                    subObj.put("value", tmp.textInput);
                } else if (tmp.type == 2) {//图片
                    subObj.put("value", tmp.upImageUrl);
                }
                obj.put("req_" + tmp.id, subObj);
            }catch (Exception e){
                CJLogger.v("getResult :" + e.toString());
            }
        }
        return obj.toString();
    }

    public void submit(){
        waitDialog.show();
        new Thread(()->{
            boolean ret = CJZManager.getInstance().taskImgSubmit(tid,model.id,getResult());
            if(ret){
                model.status = 1;
                mActicity.runOnUiThread(()->{
                    waitDialog.dismiss();
                    refreshUI();
                    MessageDialog.dialogShow(mActicity,mContext, "任务", "提交成功", new CJListener() {
                        @Override
                        public void finish(Object object) {
                            back();
                        }
                    });
                });
            }
            else{
                mActicity.runOnUiThread(()->{
                    waitDialog.dismiss();
                    CJCore.Toast(mContext,"提交失败",false);
                });
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CJHandle.getInstance().unRegister(CJHanlderType.taskImage);
    }
}
